<template>
  <view class="signal-query-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="true" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="信号查询" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 搜索框 -->
            <view class="filter-item">
              <up-search v-model="searchForm.keyword" :clearabled="true" :showAction="true" 
                placeholder="请输入设备编号或泊位号" @custom="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                  <up-button type="default" size="small" @click="handleClear" style="margin-left: 5px;">重置</up-button>
                </template>
              </up-search>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="signal-query-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              设备编号：<text class="number">{{ item.deviceId }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">泊位号：</text>
                <text class="value">{{ item.berthNumber }}</text>
              </view>
              <view class="item">
                <text class="label">心跳时间：</text>
                <text class="value">{{ item.heartbeatTime || '暂无数据' }}</text>
              </view>
              <view class="item">
                <text class="label">车检时间：</text>
                <text class="value">{{ item.vehicleDetectionTime || '暂无数据' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 搜索表单
const searchForm = reactive({
  keyword: '', // 设备编号或泊位号
});

// z-paging 组件引用
const paging = ref(null);

// 当前列表数据
const currentList = ref([]);

// 处理搜索
const handleSearch = () => {
  paging.value.reload();
};

// 处理清除
const handleClear = () => {
  searchForm.keyword = '';
  paging.value.reload();
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  });
};

// 生成随机时间
const generateRandomTime = () => {
  const now = new Date();
  const randomMinutes = Math.floor(Math.random() * 60);
  const randomHours = Math.floor(Math.random() * 24);
  const randomDays = Math.floor(Math.random() * 7);
  
  const date = new Date(now.getTime() - (randomDays * 24 * 60 * 60 * 1000) - (randomHours * 60 * 60 * 1000) - (randomMinutes * 60 * 1000));
  
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 查询列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 处理搜索参数
    const params = {
      pageNo,
      pageSize,
      keyword: searchForm.keyword
    };
    
    // 模拟API调用
    // 实际项目中应替换为真实API
    // const result = await getSignalQueryList(params);
    // const data = result.data;
    
    // 模拟数据
    const mockData = {
      total: 100,
      list: Array.from({ length: 10 }, (_, i) => {
        const deviceId = `DEV${Math.floor(Math.random() * 10000).toString().padStart(6, '0')}`;
        const berthNumber = `B${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}`;
        const hasHeartbeat = Math.random() > 0.2;
        const hasVehicleDetection = Math.random() > 0.3;
        
        // 如果有搜索关键词，则按关键词筛选
        let finalDeviceId = deviceId;
        let finalBerthNumber = berthNumber;
        
        if (searchForm.keyword) {
          if (searchForm.keyword.startsWith('DEV')) {
            finalDeviceId = searchForm.keyword;
          } else if (searchForm.keyword.startsWith('B')) {
            finalBerthNumber = searchForm.keyword;
          }
        }
        
        return {
          id: `${pageNo}-${i}`,
          deviceId: finalDeviceId,
          berthNumber: finalBerthNumber,
          heartbeatTime: hasHeartbeat ? generateRandomTime() : '',
          vehicleDetectionTime: hasVehicleDetection ? generateRandomTime() : ''
        };
      })
    };
    
    // 通知z-paging组件数据加载完成
    paging.value.complete(mockData.list);
  } catch (error) {
    console.error('获取信号查询列表数据失败:', error);
    paging.value.complete(false);
  }
};

onMounted(() => {
  // 初始页面不自动加载数据，等待用户搜索
});
</script>

<style lang="scss" scoped>
.signal-query-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .filter-section {
    margin-bottom: 10px;
    
    .filter-item {
      margin-bottom: 10px;
    }
  }
}

.signal-query-list {
  padding: 20px;
}
</style>